
import 'package:asperm/tools/widget_extension.dart';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

import '../generated/l10n.dart';

import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../tools/auth.dart';
import '../tools/const.dart';
import '../tools/divider_input_formatter.dart';
import '../tools/tools.dart';
import '../tools/user_repository.dart';
import '../views/common_button.dart';
import '../views/myDialog.dart';

class LoginPage extends StatefulWidget {
  LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {


  final nickNameController = TextEditingController();
  final passwordController = TextEditingController.fromValue(
      TextEditingValue());
  String passwordValue = '';

  String nickNameValue = '';

  bool isButtonEnabled = false;
  bool isAgreementSelected = false;
  bool isEmailLogin = false;



  final FocusNode focusNode_nickName = FocusNode();
  final FocusNode focusNode_password = FocusNode();

  int inputLength = 0;
  bool isVisitor = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

  }

  @override
  void dispose() {
    super.dispose();
    //释放
    focusNode_nickName.dispose();
    focusNode_password.dispose();

  }


  @override
  Widget build(BuildContext context) {
    // 获取屏幕大小
    final Size screenSize = MediaQuery.of(context).size;
    return Scaffold(
      body: GestureDetector(
          onTap: () {
            // 调用这个方法会隐藏软键盘
            FocusScope.of(context).unfocus();
          },
          child: ConstrainedBox(
            constraints: BoxConstraints(
              minHeight: screenSize.height, // 设置最小高度为屏幕高度
            ),
            child: Container(
              // 把Container放在SingleChildScrollView外面
              height: screenHeight(context),
              color: Colors.white,
              child: SingleChildScrollView(
                child:  Column(
                  // verticalDirection: VerticalDirection.down,
                  // mainAxisSize: MainAxisSize.max, // 添加这个属性
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        buildSmallLogo(context),
                        UsernameWidget(context),
                        buildNicknameV(context),
                        PasswordWidget(context),
                        buildPasswordV(context),
                        forgetWidget(context),
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(bottom: 40.h),
                      child: Column(
                        children: [
                          buildLoginBtn(context),
                          buildLoginGuestBtn(context),
                          signUpWidget(context),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
          )),
    );
  }


  //small logo
  Widget buildSmallLogo(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.only(top: 78.h, left: 20.w),
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            'Login',
            style: TextStyle(
              color: Color(0xff5A5A5A),
              fontSize: 30.sp,
              fontWeight: FontWeight.w700,
            ),
            textAlign: TextAlign.center,
            maxLines: 1, // 限制文本显示的最大行数为2
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    );
  }


  Widget UsernameWidget(BuildContext context) {
    return Container(
      // color: Colors.red,
      margin: EdgeInsets.only(top: 20.h, left: 20.w, right: 0.w),
      child: Container(
        child: Text(
          'Username',
          style: TextStyle(
            color: isVisitor ? Color(0xffED6D20) : Color(0xff5A5A5A),
            fontSize: 16.sp,
            fontWeight: isVisitor ? FontWeight.w600 : FontWeight.w400,
          ),
          textAlign: TextAlign.center,
          maxLines: 1,
          overflow: TextOverflow.ellipsis, // 超出部分显示省略号
        ),
      ),
    );
  }

  Widget PasswordWidget(BuildContext context) {
    return Container(
      // color: Colors.red,
      margin: EdgeInsets.only(top: 20.h, left: 20.w, right: 0.w),
      child: Container(
        child: Text(
          'Password',
          style: TextStyle(
            color: isVisitor ? Color(0xffED6D20) : Color(0xff5A5A5A),
            fontSize: 16.sp,
            fontWeight: isVisitor ? FontWeight.w600 : FontWeight.w400,
          ),
          textAlign: TextAlign.center,
          maxLines: 1,
          overflow: TextOverflow.ellipsis, // 超出部分显示省略号
        ),
      ),
    );
  }

  Widget buildLine(BuildContext context) {
    return Container(
      alignment: Alignment.topLeft,
      padding: EdgeInsets.only(top: 14.h, left: 25.w, right: 25.w),
      child: Container(
        height: 1.h,
        color: Color(0xFF4d12121D),
      ),
    );
  }


  // Email输入
  Widget buildNicknameV(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(
        left: 20.w,
        right: 20.w,
        top: 20.h,
      ),
      height: 48.h,
      decoration: BoxDecoration(
        border: Border.all(
          color: Color(0xffDADADA), // 下划线颜色
          width: 1.h, //
        ),
        borderRadius: BorderRadius.circular(4.h),
      ),
      child: Row(
        children: [
          // Email输入TextField
          SizedBox(
            width: 20.w,
          ),
          Expanded(
            child: TextField(
              focusNode: focusNode_nickName,
              // autofocus: isEmailLogin,
              controller: nickNameController,
              maxLines: 1,
              inputFormatters: [
                // 限制输入长度为 20
                LengthLimitingTextInputFormatter(20),
                // 过滤输入，只允许字母、数字、汉字和部分常见字符，不允许空格
                FilteringTextInputFormatter.allow(RegExp(r'[^\s]')),
              ],
              onChanged: (value) {
                setState(() {
                  nickNameValue = value;
                  if(passwordValue.length >0 && nickNameValue.length >0){
                    isButtonEnabled = true;
                  }else{
                    isButtonEnabled = false;
                  }
                });
              },
              decoration: InputDecoration(
                border: OutlineInputBorder(borderSide: BorderSide.none),
                // enabledBorder: UnderlineInputBorder(
                //   borderSide: BorderSide(color: Color(0xFFD8D8D8)), // 下划线颜色
                // ),
                // focusedBorder: UnderlineInputBorder(
                //   borderSide: BorderSide(color: Color(0xFFD8D8D8)), // 获得焦点时下划线颜色
                // ),
                // labelText: S.of(context).Email,
                hintText: S.of(context).EnterNickname,
                hintStyle: TextStyle(
                  fontSize: 16.sp,
                  color: Color(0xff888888),
                  fontWeight: FontWeight.w400,
                ),
                contentPadding: EdgeInsets.symmetric(
                    vertical: 0, horizontal: 0), // 调整文字位置以垂直居中
              ),
              keyboardType: TextInputType.text,
              cursorColor: Color(0xFFffED6D20),
              style: TextStyle(
                fontSize: 16.sp,
              ),
            ),
          ),
          // 取消按钮，仅当有输入时显示
          Offstage(
            offstage: nickNameValue.isEmpty,
            child: IconButton(
              alignment: Alignment.centerRight,
              icon: Icon(
                Icons.cancel,
                color: Colors.grey,
                size: 20.w,
              ),
              onPressed: () {
                setState(() {
                  nickNameValue = '';
                  nickNameController.clear();
                  if(passwordValue.length >0 && nickNameValue.length >0){
                    isButtonEnabled = true;
                  }else{
                    isButtonEnabled = false;
                  }
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget buildPasswordV(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(
        left: 20.w,
        right: 20.w,
        top: 20.h,
      ),
      height: 48.h,
      decoration: BoxDecoration(
        border: Border.all(
          color: Color(0xffDADADA), // 下划线颜色
          width: 1.h, //
        ),
        borderRadius: BorderRadius.circular(4.h),
      ),
      child: Row(
        children: [
          // Email输入TextField
          SizedBox(
            width: 20.w,
          ),
          Expanded(
            child: TextField(
              focusNode: focusNode_password,
              // autofocus: isEmailLogin,
              controller: passwordController,
              maxLines: 1,
              inputFormatters: [
                // 限制输入长度为 20
                LengthLimitingTextInputFormatter(20),
                // 过滤输入，只允许字母、数字、汉字和部分常见字符，不允许空格
                FilteringTextInputFormatter.allow(RegExp(r'[^\s]')),
              ],
              onChanged: (value) {
                setState(() {
                  passwordValue = value;
                  if(passwordValue.length >0 && nickNameValue.length >0){
                    isButtonEnabled = true;
                  }else{
                    isButtonEnabled = false;
                  }
                });
              },
              decoration: InputDecoration(
                border: OutlineInputBorder(borderSide: BorderSide.none),
                // enabledBorder: UnderlineInputBorder(
                //   borderSide: BorderSide(color: Color(0xFFD8D8D8)), // 下划线颜色
                // ),
                // focusedBorder: UnderlineInputBorder(
                //   borderSide: BorderSide(color: Color(0xFFD8D8D8)), // 获得焦点时下划线颜色
                // ),
                // labelText: S.of(context).Email,
                hintText: 'Enter Password',
                hintStyle: TextStyle(
                  fontSize: 16.sp,
                  color: Color(0xff888888),
                  fontWeight: FontWeight.w400,
                ),
                contentPadding: EdgeInsets.symmetric(
                    vertical: 0, horizontal: 0), // 调整文字位置以垂直居中
              ),
              keyboardType: TextInputType.text,
              cursorColor: Color(0xFFffED6D20),
              style: TextStyle(
                fontSize: 16.sp,
              ),
            ),
          ),
          // 取消按钮，仅当有输入时显示
          Offstage(
            offstage: passwordValue.isEmpty,
            child: IconButton(
              alignment: Alignment.centerRight,
              icon: Icon(
                Icons.cancel,
                color: Colors.grey,
                size: 20.w,
              ),
              onPressed: () {
                setState(() {
                  passwordValue = '';
                  passwordController.clear();
                  if(passwordValue.length >0 && nickNameValue.length >0){
                    isButtonEnabled = true;
                  }else{
                    isButtonEnabled = false;
                  }
                });
              },
            ),
          ),
        ],
      ),
    );
  }
  Widget forgetWidget(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 20.h, left: 20.w, right: 20.w),
      alignment: Alignment.centerLeft,
      child: Container(
        child: RichText(
          text: TextSpan(
            text: "Forget your password?",
            style: TextStyle(
              fontSize: 16.sp,
                color: globalColor(),
                fontWeight: FontWeight.w600
            ),
            recognizer:TapGestureRecognizer()
              ..onTap = () {
                //注册账号
                Navigator.pushNamed(context, '/forget_password_page');
              },
          ) ,// 字体家族根据需要设置

          ),
        ),
      );
  }


  Widget signUpWidget(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 20.h, left: 20.w, right: 20.w),
      alignment: Alignment.center,
      child: Container(
        child: RichText(
          text: TextSpan(
            text: "Don't have an account?",
            style: TextStyle(
              color: Color(0xff888888),
              fontSize: 14.sp,
            ), // 字体家族根据需要设置
            children: [
              TextSpan(
                text: ' ' + 'SIGN UP',
                style: TextStyle(
                  color: globalColor(),
                  fontWeight: FontWeight.w600
                ),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    //注册账号
                    Navigator.pushNamed(context, '/sign_up_page');
                  },
              ),
            ],
          ),
        ),
      ),
    );
  }


//登录 事件
  loginAction() async {
    // 关闭键盘
    FocusScope.of(context).unfocus();
  }


  // 登录按钮
  Widget buildLoginBtn(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(left: 20.w, right: 20.w, top: 20.h),
      // 左右各16像素的边距
      child: AspectRatio(
        aspectRatio: 335.w / 48.h, // 设置长宽比为343:50
        child: CommonButton(
          // title: S.of(context).Verification,
          title: S.of(context).Login,
          isEnable: isButtonEnabled,
          borderRadius: 5.w,
          onTap: () async {

            loginAction();
            bool isValid = await UserRepository().validateUser(nickNameValue, passwordValue);
            print('----------isValid:${isValid}');

            if (isValid) {
              showToast('登录成功');
              saveUsername(nickNameValue);
              Navigator.pushNamedAndRemoveUntil(context, '/', (route) => false);

            } else {
              showToast('登录失败，用户名或密码不正确');

            }


          },
        ),
      ),
    );
  }

  Widget buildLoginGuestBtn(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(left: 20.w, right: 20.w, top: 20.h),
      // 左右各16像素的边距
      child: AspectRatio(
        aspectRatio: 335.w / 48.h, // 设置长宽比为343:50
        child: CommonButton(
          // title: S.of(context).Verification,
          bgColor: Colors.transparent,
          title: 'Continue as Guest',
          textColor: globalColor(),
          borderRadius: 5.w,
          onTap: () {

            loginAction();
            Navigator.pushNamedAndRemoveUntil(context, '/', (route) => false);

          },
        ),
      ),
    );
  }

}
